package com.example.yuanhao.mvvm.base

import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.FitWindowsViewGroup
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import java.security.InvalidParameterException

/**
 * ================================================
 * 作   者：袁浩
 * 版   本：1.0
 * 创建日期：16/8/24
 * 描   述：
 * ================================================
 */
abstract class BaseActivity : AppCompatActivity(), IActivity {

    protected val TAG by lazy { BaseActivity::class.java.simpleName }

    /* 头部视图  */
    private var mHeaderDecor: View? = null
    //头部高度
    private var mHeaderDecorHeight: Int = 0
    //是否显示了头部
    private var mShowHeaderDecor = false
    private var isCreateHeader = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView(savedInstanceState) {
            if (it != 0) {
                bindView(it)
            } else {
                throw InvalidParameterException("The layout ID can not be 0")
            }
        }
        initData(savedInstanceState)
    }

    override fun onCreateView(parent: View?, name: String?, context: Context?, attrs: AttributeSet?): View? {

        if (!isCreateHeader && parent is FitWindowsViewGroup) {
            isCreateHeader = true
            if (parent is ViewGroup) {
                mHeaderDecor = createHeaderDecor(parent)
                addHeaderDecor(parent)
            }
        }

        return super.onCreateView(parent, name, context, attrs)
    }

    private fun addHeaderDecor(viewGroup: ViewGroup?) {
        if (viewGroup == null) {
            return
        }
        mHeaderDecor?.apply {
            mShowHeaderDecor = true
            mHeaderDecorHeight = layoutParams.height
            viewGroup.addView(this, 0)
            if (viewGroup is FrameLayout) {
                val parentParams: FrameLayout.LayoutParams = viewGroup.layoutParams as FrameLayout.LayoutParams
                parentParams.topMargin = mHeaderDecorHeight
            }
        }
    }

    /**
     * create header view
     *
     * @param parent
     */
    protected open fun createHeaderDecor(parent: ViewGroup): View? = null

    /**
     * bind view
     *
     * @param layoutId
     */
    protected open fun bindView(layoutId: Int) {
        setContentView(layoutId)
    }
}
